<?php

namespace app\admin\controller;

use app\admin\validate\SGroup as SGroupValidate;
use app\common\business\SGoods as SGoodsBus;
use app\common\business\SGroup as SGoodsGroupBus;
use app\common\business\SGroup as SGroupBus;
use app\common\lib\Check;
use app\common\lib\toCamelCase;
use app\common\model\mysql\SGoodsCategory;
use app\common\model\mysql\SGoodsGroupLadder;
use app\common\model\mysql\SGoodsGroupPlay;
use app\common\model\mysql\SGoodsGroupUser;
use app\common\model\mysql\SGoodsImage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

class SGroup extends AuthBase
{
    //轮播图选择拼团商品链接列表
    public function groupChooseList(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $groupName = $this->request->param('groupName',"");
        $groupField = $this->request->param('groupField',"");
        if($groupName){
            $where[] = ['a.group_name', 'like', '%'.$groupName.'%'];
        }
        $where[] = ['a.del_flag', '=', '0'];
        try {
            $goodsData = (new SGoodsGroupBus())->getNormalGoodsGroupData($where,$groupField,$limit,$page);
            $goodsData = (new toCamelCase())->toCamelCaseArray($goodsData);
            if($goodsData['data']){
                foreach ($goodsData['data'] as &$goodsItem) {
                    $goodsItem['url'] = '/pages/group/group/index?id='.$goodsItem['id'];
                }
            }
        }catch (\Exception $e){
            $goodsData = [];
        }
        return show(config("status.success"), "轮播图选择拼团商品链接列表", $goodsData);
    }

    //获取拼团商品数据列表查询条件
    public function groupListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $groupName = $this->request->param('groupName',"");
        $actionStatus = $this->request->param('actionStatus',"");
        if($groupName){
            $where[] = ['a.group_name', 'like', '%'.$groupName.'%'];
        }
        if ($actionStatus !== null && $actionStatus !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["a.goods_status", "=", $actionStatus];
        }
        $where[] = ['a.del_flag', '=', '0'];
        return [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where,
            'isGoods'=>true,
        ];
    }

    //拼团商品数据列表
    public function goodsGroupList(){
        $searchData = $this->groupListSearch();
        try {
            $goodsData = (new SGoodsGroupBus())->getNormalGoodsGroupData($searchData['where'],'a.*,b.main_img_url',$searchData['limit'],$searchData['page']);
            $goodsData = (new toCamelCase())->toCamelCaseArray($goodsData);
        }catch (\Exception $e){
            $goodsData = [];
        }
        return show(config("status.success"),"拼团商品数据列表",$goodsData);
    }

    //拼团商品添加
    public function goodsGroupAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $validate = new SGroupValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        // 初始化事务
        Db::startTrans();
        try {
            // 处理物流模式
            if (isset($data['logistics_mode']) && is_array($data['logistics_mode'])) {
                $data['logistics_mode'] = implode(',', $data['logistics_mode']);
            }
            // 处理活动状态
            $data['action_status'] = ($data['action_status'] === true) ? '0' : '1';
            // 处理凑团状态
            $data['gather_status'] = ($data['gather_status'] === true) ? '1' : '0';
            // 处理模拟成团状态
            if ($data['ficti_status'] === true) {
                $data['ficti_status'] = '1';
                $data['ficti_num'] = $data['ficti_num'] === 'all' ? 0 : $data['group_num'];
            } else {
                $data['ficti_status'] = '0';
                $data['ficti_num'] = 0;
            }
            $goodsData = (new SGoodsBus())->getGoodsById($data['goods_id']);
            unset($goodsData['goods_id']);
            unset($goodsData['create_by']);
            unset($goodsData['create_time']);
            unset($goodsData['update_by']);
            unset($goodsData['update_time']);
            $goodsData['goods_name'] = $data['group_name'];
            $goodsData['desc'] = $data['group_desc'];
            $goodsData['stock'] = $data['stock'];
            $goodsData['old_goods_id'] = $data['goods_id'];
            $goodsData['goods_type'] = 4;
            $goodsData['sales'] = $goodsData['order_num'] = $goodsData['goods_views'] = $goodsData['number_visitors'] = $data['number_ordered'] = $goodsData['number_favorites'] = $goodsData['status'] = $goodsData['is_extension'] = $goodsData['extension_one'] = $goodsData['extension_two'] = 0;
            $goodsData['logistics_mode'] = $data['logistics_mode'];
            $goodsAddRes = (new SGoodsBus())->addGoods($goodsData);
            if($goodsAddRes){
                $chartImgs = (new SGoodsImage())->getImages($data['goods_id']);
                (new SGoodsImage())->insertAllGoodsImage($chartImgs,$goodsAddRes);
                $map[] = ['goods_id', '=', $data['goods_id']];
                $categoryIds = (new SGoodsCategory())->getNormalGoodsFieldList($map,'category_id');
                (new SGoodsCategory())->insertAllGoodsCategory($categoryIds,$goodsAddRes);
                $data['goods_id'] = $goodsAddRes;
                //根据开始时间和结束时间判断活动状态
                // 获取当前时间
                $now = new \DateTime();
                // 创建 DateTime 对象以进行比较
                $startTime = new \DateTime($data['start_time']);
                $endTime = new \DateTime($data['end_time']);
                // 判断活动状态
                if ($startTime > $now) {
                    $data['action_status'] = '2'; // 活动未开始
                } elseif ($startTime < $now && $endTime > $now) {
                    $data['action_status'] = '0'; // 活动进行中
                } else {
                    $data['action_status'] = '1'; // 活动已结束
                }
                $result = (new SGoodsGroupBus())->addGoodsGroup($data);
                if($result){
                    (new SGoodsGroupLadder())->insertAllGroupLadder($data['set_group_data_list'],$result);
                }
            }else{
                Db::rollback();
                return show(config('status.error'),'添加商品失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"新增成功",$result);
    }

    //拼团商品修改
    public function goodsGroupEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        // 初始化事务
        Db::startTrans();
        try {
            if($data['logistics_mode']){
                $data['logistics_mode'] = implode(',',$data['logistics_mode']);
            }
            // 处理活动状态
            $data['action_status'] = ($data['action_status'] === true) ? '0' : '1';
            // 处理凑团状态
            $data['gather_status'] = ($data['gather_status'] === true) ? '1' : '0';
            // 处理模拟成团状态
            if ($data['ficti_status'] === true) {
                $data['ficti_status'] = '1';
                $data['ficti_num'] = $data['ficti_num'] === 'all' ? 0 : $data['group_num'];
            } else {
                $data['ficti_status'] = '0';
                $data['ficti_num'] = 0;
            }
            //根据开始时间和结束时间判断活动状态
            // 获取当前时间
            $now = new \DateTime();
            // 创建 DateTime 对象以进行比较
            $startTime = new \DateTime($data['start_time']);
            $endTime = new \DateTime($data['end_time']);
            // 判断活动状态
            if ($startTime > $now) {
                $data['action_status'] = '2'; // 活动未开始
            } elseif ($startTime < $now && $endTime > $now) {
                $data['action_status'] = '0'; // 活动进行中
            } else {
                $data['action_status'] = '1'; // 活动已结束
            }
            $result = (new SGroupBus())->updateById($data['goods_group_id'],$data);
            if ($result){
                //商品表修改
                $goodsData['goods_name'] = $data['group_name'];
                $goodsData['desc'] = $data['group_desc'];
                $goodsData['stock'] = $data['stock'];
                $goodsData['goods_type'] = 4;
                $goodsData['logistics_mode'] = $data['logistics_mode'];
                (new SGoodsBus())->updateById($data['goods_id'],$goodsData);
                (new SGoodsGroupLadder())->deleteGroupLadderIds($data['goods_group_id']);
                (new SGoodsGroupLadder())->insertAllGroupLadder($data['set_group_data_list'],$data['goods_group_id']);
            }
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"修改成功",$result);
    }

    //删除拼团商品
    public function goodsGroupDel(){
        $group = $this->request->param("group","","trim");
        if(empty($group)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SGroupBus())->delGoodsGroupIds($group);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //更改拼团商品状态
    public function changeStatus(){
        $goodsGroupId = $this->request->param("goodsGroupId","","trim");
        $goodsStatus = $this->request->param("goodsStatus","","trim");
        $goodsId = $this->request->param("goodsId","","trim");
        // 验证 goodsId 是否存在
        if (empty($goodsGroupId)) {
            return show(config("status.error"), "拼团商品ID不能为空");
        }
        if ($goodsStatus == "") {
            return show(config("status.error"), "商品状态不能为空");
        }
        if(empty($goodsId)){
            return show(config("status.error"), "商品ID不能为空");
        }
        try {
            $result = (new SGroupBus())->changeStatusGoods($goodsGroupId,$goodsStatus);
            if($result){
                (new SGoodsBus())->changeStatusGoods($goodsId,$goodsStatus);
            }
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"操作成功",$result);
    }

    //拼团商品详情
    public function goodsGroupDetails(){
        $group = $this->request->param("group","","trim");
        if(empty($group)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $roleData = (new SGoodsGroupBus)->getGoodsGroupById($group);
            $roleData = (new toCamelCase())->toCamelCaseArray($roleData);
        }catch (\Exception $e){
            $roleData = [];
        }
        $roleData['value1'] = [
            $roleData['startTime'],
            $roleData['endTime']
        ];
        $roleData['logisticsMode'] = explode(',',$roleData['logisticsMode']);
        // 将数组中的每个元素从字符串转换为整数
        foreach ($roleData['logisticsMode'] as &$value) {
            $value = (int)$value;
        }
        unset($value);
        if($roleData['actionStatus'] === '1'){
            $roleData['actionStatus'] = false;
        }else{
            $roleData['actionStatus'] = true;
        }
        if($roleData['gatherStatus'] === '1'){
            $roleData['gatherStatus'] = true;
        }else{
            $roleData['gatherStatus'] = false;
        }
        if($roleData['fictiStatus'] === '1'){
            $roleData['fictiStatus'] = true;
            if($roleData['fictiNum']>0){
                $roleData['groupNum'] = (int)$roleData['fictiNum'];
                $roleData['fictiNum'] = "custom";

            }else{
                $roleData['fictiNum'] = "all";
            }
        }else{
            $roleData['fictiStatus'] = false;
        }
        if($roleData['isCommission'] == 1){
            $roleData['isCommissionArr'] = [1];
        }else{
            $roleData['isCommissionArr'] = [];
        }
        $roleData['setGroupDataList'] = (new SGoodsGroupLadder())->getGroupLadder($group);
        $roleData['goodsData'] = (new SGoodsBus)->getGoodsById($roleData['goodsId'],'goods_id as goodsId,main_img_url as mainImgUrl,goods_name as goodsName,selling_price as sellingPrice,stock,status');
        return show(config("status.success"),"拼团商品详情",$roleData);
    }

    //导出拼团商品数据信息
    public function exportGoodsGroup(){
        $searchData = $this->groupListSearch();
        $postCount = (new SGoodsGroupBus())->getNormalGoodsGroupCount($searchData['where']);
        $configData = (new SGoodsGroupBus())->getNormalGoodsGroupData($searchData['where'],'a.*,b.main_img_url',$postCount,$searchData['page']);

        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:H1'); // 假设表头只有5列
        $sheet->setCellValue('A1', '拼团商品数据信息');
        // 设置表头
        $header = ['主键ID', '拼团图片', '拼团名称', '成团数量', '活动状态','结束时间','商品状态','拼团时效(单位 小时)'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F','G','H']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(21);
        }
        // 填充数据
        $row = 3;
        foreach ($configData['data'] as $post) {
            $post['main_img_url'] = (new Check())->checkUrl($post['main_img_url']);
            $post['action_status'] = $post['action_status'] == '1'?'已结束':'进行中';
            $post['goods_status'] = $post['goods_status'] == '1'?'下架':'上架';
            $sheet->setCellValue('A' . $row, $post['goods_group_id']);
            $sheet->setCellValue('B' . $row, $post['main_img_url']);
            $sheet->setCellValue('C' . $row, $post['group_name']);
            $sheet->setCellValue('D' . $row, $post['success_num']);
            $sheet->setCellValue('E' . $row, $post['action_status']);
            $sheet->setCellValue('F' . $row, $post['end_time']);
            $sheet->setCellValue('G' . $row, $post['goods_status']);
            $sheet->setCellValue('H' . $row, $post['time']);
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:H2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:H2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':H' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':H' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="goods_group.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }

    /********************** 拼团列表管理 **************************/
    public function groupBuyingList(){
        $where = [];
        // 获取分页参数
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);
        $endTime = $this->request->param('endTime',"");
        $status = $this->request->param('status',"");
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["a.status", "=", $status];
        }
        if($endTime){
            $where[] = ['a.end_time',">=",$endTime[0]." 00:00:00"];
            $where[] = ['a.end_time',"<=",$endTime[1]." 23:59:59"];
        }
        $where[] = ['a.del_flag', '=', '0'];
        $where[] = ['b.is_initiator', '=', '0'];
        try {
            $groupBuyingData = (new SGroupBus())->getNormalGoodsGroupBuyingData($where,'a.*,b.order_id,b.uid,b.nickname,b.avatar,c.group_name',$limit,$page);
            $groupBuyingData = (new toCamelCase())->toCamelCaseArray($groupBuyingData);
        }catch (\Exception $e){
            $groupBuyingData = [];
        }
        return show(config("status.success"),"拼团列表数据",$groupBuyingData);
    }

    //拼团成员详情
    public function groupUserList(){
        $buying = $this->request->param("buying","","trim");
        if(empty($buying)){
            return show(config("status.error"),"参数不能为空");
        }
        $where[] = ['a.group_buying_id', '=', $buying];
        $where[] = ['a.del_flag', '=', '0'];
        try {
            $groupUserData = (new SGoodsGroupUser())->getGroupUserList($where,'a.*,b.order_sn,pay_price');
            $groupUserData = (new toCamelCase())->toCamelCaseArray($groupUserData);
        }catch (\Exception $e){
            $groupUserData = [];
        }
        return show(config("status.success"),"拼团成员详情数据",$groupUserData);
    }

    //拼团玩法详情
    public function goodsGroupPlayDetails(){
        $goodsGroupPlayId = $this->request->param("goodsGroupPlayId","","trim");
        if(empty($goodsGroupPlayId)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $groupUserData = (new SGoodsGroupPlay())->getGoodsGroupPlayByIdFind($goodsGroupPlayId,"goods_group_play_id,goods_group_play_details");
            $groupUserData = (new toCamelCase())->toCamelCaseArray($groupUserData);
        }catch (\Exception $e){
            $groupUserData = [];
        }
        return show(config("status.success"),"拼团玩法详情",$groupUserData);
    }

    //拼团玩法详情修改
    public function goodsGroupPlayEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        // 初始化事务
        Db::startTrans();
        try {
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $result = (new SGoodsGroupPlay())->updateById($data['goods_group_play_id'],$data);
        }catch (\Exception $e){
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        }
        Db::commit();
        return show(config("status.success"),"修改成功",$result);
    }
}
